import { Component, OnInit, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver, EventEmitter } from '@angular/core';
import { ReviewPageService } from "./review-page.service";
import { InvestService } from "../../../invest.service";
import { ReviewQueryPageComponent } from "../../review/review-query-page/review-query-page.component";
import { AppPaginationComponent, PaginationModel } from "app/widgets/pagination/pagination.component";
import { environment } from 'environments/environment';
import { FlowComponent } from "../../../modal/flow/flow.component";
import { ReviewComponent } from "../../../modal/review/review.component";
import * as _ from 'lodash';
import { DataService } from 'app/services/data.service';
import { TableComponent } from "../../../modal/table/table.component";

@Component({
  selector: 'app-review-page',
  templateUrl: './review-page.component.html',
  styleUrls: ['./review-page.component.scss'],
  providers: [ReviewPageService]
})
export class ReviewPageComponent implements OnInit {
  // 复核模版
  @ViewChild("reviews", { read: ViewContainerRef })
  reviews: ViewContainerRef;
  reviewComponent: ComponentRef<ReviewComponent>;
  // 指标复核查询模版
  @ViewChild("reviewQueryPage", { read: ViewContainerRef })
  reviewQueryPage: ViewContainerRef;
  reviewQueryPageComponent: ComponentRef<ReviewQueryPageComponent>;
  // 查看流程状态模版
  @ViewChild("flow", { read: ViewContainerRef })
  flow: ViewContainerRef;
  flowComponent: ComponentRef<FlowComponent>;
  // 模版
  @ViewChild("reviewTable", { read: ViewContainerRef })
  reviewTable: ViewContainerRef;
  reviewTableComponent: ComponentRef<TableComponent>;
  // lodash
  public _: any = _;
  // 菜单数据
  public menuData: any;
  // 菜单权限set
  public menuResourceSet: any = [];
  // 列表是否全选
  public isCheckedAll = false;
  // 列表数据
  public dataList: any;
  // 克隆列表新数据,用于页面数据标红对比
  public isChangeList: any = [];
  // 用于是否显示下拉框
  public isEditList: any = [];
  // 复核分页列表post
  public getBody = {
    pageIndex: 1,
    pageSize: 20,
    sFullName: '',
    sFundCode: '',
    sFundType: '',
    disposeStatus: ''
  }
  // 列表分页配置
  public listPageInfo = {
    currentPageNum: 1,
    pageSize: 20,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 20, 50, 100]
  }
  // 字典值
  public dictionaryList: any = {
    FUND_TYPE: []
  };
  // 当前用户
  public user: any;

  constructor(
    public resolver: ComponentFactoryResolver,
    public reviewPageService: ReviewPageService,
    public investService: InvestService,
    public dataService: DataService
  ) {
    let that = this;
    // 用于指标复核/返回操作后刷新列表
    this.investService.targetReview = new EventEmitter();
    this.investService.targetReview.subscribe((data: any) => {
      if (data) {
        that.list();
      }
    })
  }

  ngOnInit() {
    let that = this;
    // 权限处理
    this.dataService.initTree.subscribe((data) => {
      if (data) {
        let SessionMenuData = sessionStorage.getItem('menu');
        this.menuData = JSON.parse(SessionMenuData)
        this.menuResourceSet = [];
        _.forEach(this.menuData, (item, index) => {
          if (item.sName == '风控管理') {
            _.forEach(item.children, (it, idx) => {
              if (it.sName == '投资范围指标') {
                _.forEach(it.children, (ite, i) => {
                  if (ite.sName == '指标复核') {
                    that.menuResourceSet = ite.resourceSet
                    sessionStorage.setItem('btn-rcmi', this.menuResourceSet);
                  }
                })
              }
            })
          }
        })
      }
    })
    let SessionMenuData = sessionStorage.getItem('menu');
    this.menuData = JSON.parse(SessionMenuData)
    this.menuResourceSet = [];
    _.forEach(this.menuData, (item, index) => {
      if (item.sName == '风控管理') {
        _.forEach(item.children, (it, idx) => {
          if (it.sName == '投资范围指标') {
            _.forEach(it.children, (ite, i) => {
              if (ite.sName == '指标复核') {
                that.menuResourceSet = ite.resourceSet
                sessionStorage.setItem('btn-rcmi', this.menuResourceSet);
              }
            })
          }
        })
      }
    })
    // 加载table
    this.showReviewTable();
    // 字典值
    this.dictionaryList = JSON.parse(localStorage.getItem("dictionaryList"));
    // 获取当前用户
    this.user = sessionStorage.getItem('username');
    this.list();
  }
  // 复核分页
  list(pageNum?, pageSize?) {
    let that = this;
    this.isCheckedAll = false;
    this.getBody.sFullName = _.trim(this.getBody.sFullName);
    this.getBody.sFundCode = _.trim(this.getBody.sFundCode);
    this.getBody.pageIndex = pageNum ? pageNum : this.listPageInfo.currentPageNum;
    this.getBody.pageSize = pageSize ? pageSize : this.listPageInfo.pageSize;
    this.activeTab('targetReview');
    new Promise((resolve, reject) => {
      this.reviewPageService.list(this.getBody).subscribe(data => {
        if (data) {
          that.dataList = data.list;
          that.listPageInfo.currentPageNum = data.pageNum;
          that.listPageInfo.totalPages = data.pages;
          that.listPageInfo.total = data.total;
          that.listPageInfo.startRow = data.startRow;
          that.listPageInfo.endRow = data.endRow;
          // 用于标红对比
          that.isChangeList = _.cloneDeep(data.list);
          // 用于是否显示下拉框
          that.isEditList = _.cloneDeep(data.list);
          _.forEach(that.dataList, (item, index: any) => {
            if (index > 0 && (index + 1) % 2 == 0) {
              // 前后条数据对比(新数据)
              _.forIn(item, (value, key) => {
                if (that.dataList[index - 1][key] == that.dataList[index][key]) {
                  that.isChangeList[index][key] = false;
                  that.isEditList[index][key] = 'no';
                } else {
                  that.isChangeList[index][key] = true;
                  that.isEditList[index][key] = 'no';
                }
              })
            } else {
              // 旧数据不做对比
              _.forIn(item, (value, key) => {
                that.isChangeList[index][key] = false;
                that.isEditList[index][key] = 'no';
              })
            }
          })
          resolve(data);
        }
      })
    }).then(data => {
      that.reviewTableComponent.instance.isCheckedAll = false;
      that.reviewTableComponent.instance.dataList = _.cloneDeep(that.dataList);
      that.reviewTableComponent.instance.isChangeList = _.cloneDeep(that.isChangeList);
      that.reviewTableComponent.instance.isEditList = _.cloneDeep(that.isEditList);
    })
  }
  // 分页
  sizeChange(pageSize: number) {
    if (pageSize !== this.listPageInfo.pageSize) {
      this.listPageInfo.pageSize = pageSize;
      this.list();
    }
  }
  // 分页
  pageNavigation(currentPageNum: number) {
    this.listPageInfo.currentPageNum = currentPageNum;
    this.list(this.listPageInfo.currentPageNum, this.listPageInfo.pageSize);
  }
  // 复核、返回
  reviewOrReback(operate) {
    let that = this;
    let checkedItem = [];
    let userList = [];
    let tips = [];
    _.forEach(this.reviewTableComponent.instance.dataList, item => {
      if (item.isChecked) {
        checkedItem.push(item);
        userList.push(item.sOpr);
      }
    });
    if (checkedItem.length == 0) {
      window['swal']("提示", "请选择一条或多条记录", "warning");
    } else {
      // 判断是否包含当前用户操作的数据
      if (_.includes(userList, this.user)) {
        _.forEach(checkedItem, it => {
          if (it.sOpr == that.user) {
            tips.push(it.sFullName);
          }
        })
        let sTips = tips.join(",");
        window['swal']("提示", sTips + " 由本人修改,不能执行该操作", "warning");
      } else {
        this.showReview(checkedItem, operate);
      }
    }
  }
  // 显示模版
  showModel(type) {
    let that = this;
    let checkedItem = [];
    _.forEach(this.reviewTableComponent.instance.dataList, item => {
      if (item.isChecked) {
        checkedItem.push(item);
      }
    });
    if (checkedItem.length == 1) {
      switch (type) {
        case 'flow':
          this.showFlow(checkedItem[0]);
          break;
      }
    } else if (checkedItem.length < 1) {
      window['swal']("提示", "请选择一条记录", "warning");
    } else if (checkedItem.length > 1) {
      window['swal']("提示", "只能选择一条记录", "warning");
    }
  }
  // 复核模版
  showReview(item, operate) {
    if (this.reviewComponent && this.reviewComponent.instance) {
      this.reviewComponent.destroy();
    }
    const reviewComponent = this.resolver.resolveComponentFactory(ReviewComponent);
    this.reviewComponent = this.reviews.createComponent(reviewComponent);
    this.reviewComponent.instance.operate = operate;
    this.reviewComponent.instance.dataList = item;
    window['$']('#reviews').modal('show');
  }
  // 查看流程状态模版
  showFlow(item) {
    if (this.flowComponent && this.flowComponent.instance) {
      this.flowComponent.destroy();
    }
    const flowComponent = this.resolver.resolveComponentFactory(FlowComponent);
    this.flowComponent = this.flow.createComponent(flowComponent);
    this.flowComponent.instance.getFlowBody.nIjId = item.nIjId;
    this.flowComponent.instance.getFlowBody.nIxId = item.nFundNo;
    this.flowComponent.instance.getFlowBody.nFlowId = item.nFlowId;
    this.flowComponent.instance.getBody.nIjId = item.nIjId;
    this.flowComponent.instance.getBody.nIxId = item.nFundNo;
    this.flowComponent.instance.getBody.nFlowId = item.nFlowId;
    this.flowComponent.instance.type = 'review';
    window['$']('#targetReviewFlow').modal('show');
  }
  getList(index: any) {
    let that = this;
    that.activeTab(index);
    switch (index) {
      case 'targetReview':
        that.list();
        break;
      case 'targetReviewQuery':
        that.showTargetReviewQuery();
        break;
    }
  }
  // 切换tab
  activeTab(index: any) {
    let that = this;
    window['$']('#reviewTab').removeClass('active');
    window['$']('#review').removeClass('active');
    window['$']('#reviewQueryTab').removeClass('active');
    window['$']('#reviewQuery').removeClass('active');
    switch (index) {
      case 'targetReview':
        window['$']('#reviewTab').addClass('active');
        window['$']('#review').addClass('active');
        break;
      case 'targetReviewQuery':
        window['$']('#reviewQueryTab').addClass('active');
        window['$']('#reviewQuery').addClass('active');
        break;
    }
  }
  // 复核查询模版
  showTargetReviewQuery() {
    if (this.reviewQueryPageComponent && this.reviewQueryPageComponent.instance) {
      this.reviewQueryPageComponent.destroy();
    }
    const reviewQueryPageComponent = this.resolver.resolveComponentFactory(ReviewQueryPageComponent);
    this.reviewQueryPageComponent = this.reviewQueryPage.createComponent(reviewQueryPageComponent);
  }
  // 模版
  showReviewTable() {
    if (this.reviewTableComponent && this.reviewTableComponent.instance) {
      this.reviewTableComponent.destroy();
    }
    const reviewQueryTableComponent = this.resolver.resolveComponentFactory(TableComponent);
    this.reviewTableComponent = this.reviewTable.createComponent(reviewQueryTableComponent);
    this.reviewTableComponent.instance.isReviewPage = 'yes';
    this.reviewTableComponent.instance.isShowCol1 = 'sFundTypeZh';
    this.reviewTableComponent.instance.isShowCol2 = 'sFullName';
    this.reviewTableComponent.instance.isShowCol3 = 'sOprStateZh';
  }
}
